﻿using System;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using System.Windows;
using System.Windows.Input;
using JXPlatform.GIS.Views;
using JXPlatform.Infrastructure;
using Microsoft.Practices.Prism.Commands;
using Microsoft.Practices.Prism.Regions;
using System.Linq;

namespace JXPlatform.Demo.ViewModels
{
    [Export]
    public class ShellViewModel : DependencyObject
    {
        private readonly IRegionManager _regionManager;

        [ImportingConstructor]
        public ShellViewModel(IRegionManager regionManager)
        {
            if (regionManager == null)
            {
                throw new ArgumentNullException("regionManager");
            }

            _regionManager = regionManager;

            InitializeCommands();
        }

        private void InitializeCommands()
        {
            PointListCommand = new DelegateCommand<object>(OnPointListCommand, CanPointListCommand);
            MapCommand = new DelegateCommand<object>(OnMapCommand, CanExecuteMapCommand);
        }

        private bool CanExecuteMapCommand(object arg)
        {
            return true;
        }

        private void OnMapCommand(object obj)
        {
            if (!_regionManager.Regions.ContainsRegionWithName(RegionNames.MainRegion))
            {
                return;
            }

            var mainRegion = _regionManager.Regions[RegionNames.MainRegion];

            var viewName = typeof(MapView).FullName;
            var view = mainRegion.GetView(viewName);
            if (view == null)
            {
                view = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<MapView>();
                mainRegion.Add(view, viewName);
            }

            mainRegion.Activate(view);           
        }

        public ICommand MapCommand { get; private set; }

        public ICommand PointListCommand { get; private set; }
        private void OnPointListCommand(object arg)
        {
            if (!_regionManager.Regions.ContainsRegionWithName(RegionNames.MainRegion))
            {
                return;
            }

            var mainRegion = _regionManager.Regions[RegionNames.MainRegion];
            var viewName = typeof (PointListView).FullName;
            var view = mainRegion.GetView(viewName);
            if (view == null)
            {
                view = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<PointListView>();
                mainRegion.Add(view, viewName);
            }

            mainRegion.Activate(view);
        }
        private bool CanPointListCommand(object arg)
        {
            return true;
        }
    }
}
